package vashion.azeroth.core.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import vashion.azeroth.api.result.Result;
import vashion.azeroth.contant.AzerothConstants;
import vashion.azeroth.contant.FollowErrorEnum;
import vashion.azeroth.contant.GenericErrorEnum;
import vashion.azeroth.context.pojo.PersonalFollowContext;
import vashion.azeroth.core.manager.personal.PersonalFollowManager;
import vashion.azeroth.core.manager.personal.PersonalMemberManager;
import vashion.azeroth.core.manager.personal.PersonalMemberVipManager;
import vashion.azeroth.core.personal.pojo.PersonalFollow;
import vashion.azeroth.core.personal.pojo.PersonalMember;
import vashion.azeroth.core.personal.pojo.PersonalMemberVip;
import vashion.azeroth.core.result.ApiResult;
import vashion.azeroth.core.service.PersonalFollowService;
import vashion.azeroth.core.service.PersonalMemberService;
import vashion.azeroth.core.service.PersonalProfilesService;

@Service
public class PersonalFollowServiceImpl<T> implements PersonalFollowService<T> {

	private final static Logger log = LoggerFactory
			.getLogger(PersonalFollowServiceImpl.class);

	@Autowired
	PersonalFollowManager personalFollowManager;

	@Autowired
	PersonalMemberService personalMemberService;

	@Autowired
	PersonalProfilesService personalProfilesService;

	@Autowired
	PersonalMemberManager personalMemberManager;

	@Autowired
	PersonalMemberVipManager personalMemberVipManager;

	/**
	 * 关注粉丝
	 * */

	@Override
	public ApiResult<Boolean> addFollow(PersonalFollow personalFollow) {

		ApiResult<Boolean> result = paramCheck(personalFollow);

		if (!result.isSuccess()) {

			return result;

		}

		try {

			// 如果是黑名单，不允许添加关注
			personalFollow
					.setStatus(AzerothConstants.PersonalFollow.PersonalFollowStatus.BLACK);

			int num = personalFollowManager.findCnt(personalFollow);

			if (num > 0) {

				return ApiResult.newErrorResult(
						FollowErrorEnum.IN_BLACK_LIST.getErrorCode(),
						FollowErrorEnum.IN_BLACK_LIST.getErrorMessage(), false);
			}

			// 先查询是否已关注，如果已关注，返回

			personalFollow
					.setStatus(AzerothConstants.PersonalFollow.PersonalFollowStatus.NORMAL);

			num = personalFollowManager.findCnt(personalFollow);

			if (num > 0) {

				return ApiResult
						.newErrorResult(FollowErrorEnum.ALREADY_FOLLOW
								.getErrorCode(), FollowErrorEnum.ALREADY_FOLLOW
								.getErrorMessage(), false);
			}

			// 需要查询一下是否相互关注

			PersonalFollow newPersonalFollow = new PersonalFollow();

			newPersonalFollow.setMemberId(personalFollow.getFansMemberId());

			newPersonalFollow.setFansMemberId(personalFollow.getMemberId());

			List<PersonalFollow> personalFollowList = personalFollowManager
					.find(newPersonalFollow);

			if (personalFollowList != null && personalFollowList.size() == 1) {

				// 说明相互关注
				personalFollow.setRemark("2");

				// 此时需要更新上一张表

				personalFollowList.get(0).setRemark("2");

				personalFollowList.get(0).setTimeEdit(new Date());

				personalFollowManager.update(personalFollowList.get(0));

			} else {

				personalFollow.setRemark("1");
			}

			// 补合参数
			fillParam(personalFollow);

			// 插入数据
			Date date = new Date();
			personalFollow.setTimeAdd(date);
			personalFollow.setTimeEdit(date);

			PersonalFollow pf = personalFollowManager.save(personalFollow);

			if (pf != null) {

				// 会员增加一个粉丝
				Long memberId = pf.getMemberId();
				int type = 2;
				String action = "up";
				Boolean b = personalProfilesService.updateFansCount(memberId,
						type, action);

				if (!b) {

					return ApiResult.newErrorResult(
							FollowErrorEnum.PROFILE_WRITE_ERROR.getErrorCode(),
							FollowErrorEnum.PROFILE_WRITE_ERROR
									.getErrorMessage(), false);
				}

				// 粉丝增加一个关注

				Long fansMember = pf.getFansMemberId();
				type = 1;
				action = "up";

				b = personalProfilesService.updateFansCount(fansMember, type,
						action);
				if (b == null || !b) {

					return ApiResult.newErrorResult(
							FollowErrorEnum.PROFILE_WRITE_ERROR.getErrorCode(),
							FollowErrorEnum.PROFILE_WRITE_ERROR
									.getErrorMessage(), false);
				}

				return ApiResult.newSuccessResult(true);

			}
		} catch (Exception e) {

			log.error(e.getMessage() + e.toString());

			return ApiResult.newErrorResult(
					GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}

		return result;
	}

	@Override
	public ApiResult<Boolean> cancelFollow(PersonalFollow personalFollow) {

		ApiResult<Boolean> result = paramCheck(personalFollow);

		// 参数校验
		if (!result.isSuccess()) {

			return result;
		}

		try {

			// 先查询是否已关注，如果已关注，返回

			personalFollow
					.setStatus(AzerothConstants.PersonalFollow.PersonalFollowStatus.NORMAL);

			List<PersonalFollow> list = personalFollowManager
					.find(personalFollow);

			if (list.size() == 0) {

				return ApiResult.newErrorResult(
						FollowErrorEnum.NOT_FOLLOW.getErrorCode(),
						FollowErrorEnum.NOT_FOLLOW.getErrorMessage(), false);
			}

			personalFollow = list.get(0);
			// 构造参数
			personalFollow
					.setStatus(AzerothConstants.PersonalFollow.PersonalFollowStatus.DELETE);

			Date timeEdit = new Date();
			personalFollow.setTimeEdit(timeEdit);

			int count = personalFollowManager.update(personalFollow);

			// 去除关联关系

			PersonalFollow newPersonalFollow = new PersonalFollow();

			newPersonalFollow.setMemberId(personalFollow.getFansMemberId());

			newPersonalFollow.setFansMemberId(personalFollow.getMemberId());

			List<PersonalFollow> personalFollowList = personalFollowManager
					.find(newPersonalFollow);

			if (personalFollowList != null && personalFollowList.size() == 1) {

				personalFollowList.get(0).setRemark("1");

				// 更新一下操作,去除相互关联关系

				personalFollowManager.update(personalFollowList.get(0));

			}

			// 去除表结构里的数量

			if (count > 0) {

				// 会员减少一个粉丝
				Long memberId = personalFollow.getMemberId();
				int type = 2;
				String action = "down";
				Boolean b = personalProfilesService.updateFansCount(memberId,
						type, action);

				if (!b) {

					return ApiResult.newErrorResult(
							FollowErrorEnum.PROFILE_WRITE_ERROR.getErrorCode(),
							FollowErrorEnum.PROFILE_WRITE_ERROR
									.getErrorMessage(), false);
				}

				// 粉丝减少一个关注

				Long fansMemberId = personalFollow.getFansMemberId();
				type = 1;
				action = "down";

				b = personalProfilesService.updateFansCount(fansMemberId, type,
						action);
				if (!b) {

					return ApiResult.newErrorResult(
							FollowErrorEnum.PROFILE_WRITE_ERROR.getErrorCode(),
							FollowErrorEnum.PROFILE_WRITE_ERROR
									.getErrorMessage(), false);
				}

				return ApiResult.newSuccessResult(true);
			} else {

				return ApiResult.newErrorResult(
						GenericErrorEnum.UPDATE_ERROR.getErrorCode(),
						GenericErrorEnum.UPDATE_ERROR.getErrorMessage(), false);
			}

			/**
			 * @TODO 修改profile数据
			 * 
			 * */

		} catch (Exception e) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage(), false);

		}

	}

	@Override
	public ApiResult<List<PersonalFollowContext>> findFollowdByMe(
			Long memberId, Integer pageNum, Integer pageSize) {

		// 构造参数
		PersonalFollow pf = new PersonalFollow();

		pf.setFansMemberId(memberId);

		pf.setStatus(AzerothConstants.PersonalFollow.PersonalFollowStatus.NORMAL);

		pf.setFirstRow(pageNum);

		pf.setPageSize(pageSize);

		try {

			int totalCount = personalFollowManager.findCnt(pf);

			List<PersonalFollow> personalFollowList = personalFollowManager
					.find(pf);

			List<PersonalFollowContext> personalFollowContextList = convertParam(
					personalFollowList, 2);

			return ApiResult.newSuccessResult(personalFollowContextList,
					totalCount);

		} catch (Exception e) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());

		}

	}

	@Override
	public ApiResult<List<PersonalFollowContext>> findMyFollow(
			Long memberId, Integer pageNum, Integer pageSize) {

		Result<List<PersonalFollow>> result = new Result();

		// 构造参数
		PersonalFollow pf = new PersonalFollow();

		pf.setMemberId(memberId);

		pf.setFirstRow(pageNum);

		pf.setPageSize(pageSize);

		pf.setStatus(AzerothConstants.PersonalFollow.PersonalFollowStatus.NORMAL);

		try {

			int totalCount = personalFollowManager.findCnt(pf);

			List<PersonalFollow> personalFollowList = personalFollowManager
					.find(pf);

			// type = 1 关注我的人
			List<PersonalFollowContext> personalFollowContextList = convertParam(
					personalFollowList, 1);

			return ApiResult.newSuccessResult(personalFollowContextList,
					totalCount);

		} catch (Exception e) {
			return ApiResult.newErrorResult(
					GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());

		}

	}

	@Override
	public ApiResult<Integer> isFollowed(Long fansMemberId, Long memberId) {

		// 构造参数
		PersonalFollow pf = new PersonalFollow();

		pf.setFansMemberId(fansMemberId);

		pf.setMemberId(memberId);

		pf.setStatus(AzerothConstants.PersonalFollow.PersonalFollowStatus.NORMAL);

		try {

			// int cnt = personalFollowManager.findCnt(pf);
			//
			// if (cnt >= 1) {
			//
			// return ApiResult.newSuccessResult(true);
			// } else {
			//
			// return ApiResult.newSuccessResult(false);
			// }

			List<PersonalFollow> personalFollowList = personalFollowManager
					.find(pf);

			if (personalFollowList != null & personalFollowList.size() == 1) {

				PersonalFollow personalFollow = personalFollowList.get(0);

				Integer relation = Integer.valueOf(personalFollow.getRemark());

				return ApiResult.newSuccessResult(relation);

			}

			return ApiResult.newSuccessResult(0);

		} catch (Exception e) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());

		}

	}

	private ApiResult<Boolean> paramCheck(PersonalFollow personalFollow) {

		if (null == personalFollow.getMemberId()) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EMPTY.getErrorCode(), "会员ID"
							+ GenericErrorEnum.NOT_EMPTY.getErrorMessage(),
					false);
		}

		if (null == personalFollow.getFansMemberId()) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.NOT_EMPTY.getErrorCode(), "粉丝ID"
							+ GenericErrorEnum.NOT_EMPTY.getErrorMessage(),
					false);

		}

		if (personalFollow.getFansMemberId().equals(
				personalFollow.getMemberId())) {

			return ApiResult.newErrorResult(
					GenericErrorEnum.CAN_NOT_FOLLOW_MYSELF.getErrorCode(),
					GenericErrorEnum.CAN_NOT_FOLLOW_MYSELF.getErrorMessage(),
					false);

		}

		Long memberId = personalFollow.getMemberId();

		String memberName = personalFollow.getMemberName();

		ApiResult<Boolean> result = checkMemberExist(memberId, memberName);

		if (!result.isSuccess()) {

			return result;
		}

		Long fansMemberId = personalFollow.getFansMemberId();

		String fansMemberName = personalFollow.getFansMemberName();

		result = checkMemberExist(fansMemberId, fansMemberName);

		if (!result.isSuccess()) {

			return result;
		}

		return ApiResult.newSuccessResult(true);

	}

	public ApiResult<Boolean> checkMemberExist(Long memberId,
			String memberName) {

		// if (true) {
		//
		// // 用于测试
		// return ApiResult.newSuccessResult();
		// }

		PersonalMember personalMember = new PersonalMember();

		personalMember.setMemberId(memberId);

		// personalMember.setMemberName(memberName);

		ApiResult<PersonalMember> result = personalMemberService
				.checkMember(personalMember);

		if (result.isSuccess()) {
			return ApiResult.newSuccessResult();
		} else {

			return ApiResult.newErrorResult(result.getErrorCode(),
					result.getErrorMsg(), false);
		}

	}

	public void fillParam(PersonalFollow personalFollow) {

		Long memberId = personalFollow.getMemberId();

		Long fansMemberId = personalFollow.getFansMemberId();

		PersonalMember personalMember = personalMemberManager.get(memberId);

		if (personalMember != null) {

			personalFollow.setMemberName(personalMember.getMemberName());
		}

		personalMember = personalMemberManager.get(fansMemberId);

		if (personalMember != null) {

			personalFollow.setFansMemberName(personalMember.getMemberName());
		}

	}

	public List<PersonalFollowContext> convertParam(
			List<PersonalFollow> personalFollowList, int type) {

		List<PersonalFollowContext> personalFollowContextList = new ArrayList<PersonalFollowContext>();

		if (personalFollowList == null || personalFollowList.size() == 0) {

			return personalFollowContextList;
		}

		for (PersonalFollow personalFollow : personalFollowList) {

			PersonalFollowContext personalFollowContext = new PersonalFollowContext();

			personalFollowContext.setFollowId(personalFollow.getFollowId());

			personalFollowContext.setMemberId(personalFollow.getMemberId());

			personalFollowContext.setMemberName(personalFollow.getMemberName());

			personalFollowContext.setFansMemberId(personalFollow
					.getFansMemberId());

			personalFollowContext.setFansMemberName(personalFollow
					.getFansMemberName());

			personalFollowContext.setStatus(personalFollow.getStatus());

			personalFollowContext.setTimeAdd(personalFollow.getTimeAdd());

			personalFollowContext.setTimeEdit(personalFollow.getTimeEdit());

			Long memberId = 0L;

			if (type == 1) {

				// 关注我的人

				memberId = personalFollowContext.getFansMemberId();

			} else if (type == 2) {

				// 我关注的人

				memberId = personalFollowContext.getMemberId();
			}

			PersonalMember personalMember = personalMemberManager.get(memberId);

			PersonalMemberVip personalMemberVip = personalMemberVipManager
					.get(memberId);

			if (personalMember != null) {

				personalFollowContext.setNickName(personalMember.getNickName());

				personalFollowContext.setHeadImg(personalMember.getHeadImg());

				personalFollowContext.setRelation(personalFollow.getRemark());

			}

			if (personalMemberVip != null) {

				personalFollowContext.setVipLevel(personalMemberVip
						.getVipLevel() == null ? "0" : personalMemberVip
						.getVipLevel());

			}

			personalFollowContextList.add(personalFollowContext);

		}

		return personalFollowContextList;
	}

	@Override
	public ApiResult<Boolean> followInBlackList(PersonalFollow personalFollow) {

		ApiResult<Boolean> result = paramCheck(personalFollow);

		// 参数校验
		if (!result.isSuccess()) {

			return result;
		}

		try {

			// 先查询是否已关注，如果已关注，直接修改为黑名单

			List<PersonalFollow> followList = personalFollowManager
					.find(personalFollow);

			List<PersonalFollow> list = filter(followList);

			if (list.size() == 0) {

				// 如果没有数据，直接插入一条
				personalFollow
						.setStatus(AzerothConstants.PersonalFollow.PersonalFollowStatus.BLACK);

				// 补合参数
				fillParam(personalFollow);

				// 插入数据
				Date date = new Date();
				personalFollow.setTimeAdd(date);
				personalFollow.setTimeEdit(date);

				PersonalFollow pf = personalFollowManager.save(personalFollow);

				// return ApiResult.newSuccessResult(true);

			} else {

				// 默认只会有一条记录为1

				// 否则进行更新操作
				PersonalFollow queryPersonalFollow = list.get(0);

				if (queryPersonalFollow
						.getStatus()
						.equals(AzerothConstants.PersonalFollow.PersonalFollowStatus.BLACK)) {

					return ApiResult.newErrorResult(
							FollowErrorEnum.ALREADY_IN_BLACK.getErrorCode(),
							FollowErrorEnum.ALREADY_IN_BLACK.getErrorMessage());
				}

				queryPersonalFollow
						.setStatus(AzerothConstants.PersonalFollow.PersonalFollowStatus.BLACK);

				queryPersonalFollow.setTimeEdit(new Date());

				int num = personalFollowManager.update(queryPersonalFollow);

				// return ApiResult.newSuccessResult(true);

			}

			//-----------------------返向业务----------------------------
			
			PersonalFollow newPersonalFollow = new PersonalFollow();

			newPersonalFollow.setFansMemberId(personalFollow.getMemberId());
			newPersonalFollow.setMemberId(personalFollow.getFansMemberId());

			// 先查询是否已关注，如果已关注，直接修改为黑名单

			followList = personalFollowManager.find(newPersonalFollow);

			list = filter(followList);

			if (list.size() == 0) {

				// 如果没有数据，直接插入一条
				newPersonalFollow
						.setStatus(AzerothConstants.PersonalFollow.PersonalFollowStatus.BLACK);

				// 补合参数
				fillParam(newPersonalFollow);

				// 插入数据
				Date date = new Date();
				newPersonalFollow.setTimeAdd(date);
				newPersonalFollow.setTimeEdit(date);

				PersonalFollow pf = personalFollowManager
						.save(newPersonalFollow);

			} else {

				// 默认只会有一条记录为1

				// 否则进行更新操作
				PersonalFollow queryPersonalFollow = list.get(0);

				if (queryPersonalFollow
						.getStatus()
						.equals(AzerothConstants.PersonalFollow.PersonalFollowStatus.BLACK)) {

					log.error("关注返向数据已在黑名单");
					
					return ApiResult.newErrorResult(
							FollowErrorEnum.ALREADY_IN_BLACK.getErrorCode(),
							FollowErrorEnum.ALREADY_IN_BLACK.getErrorMessage());
				}

				queryPersonalFollow
						.setStatus(AzerothConstants.PersonalFollow.PersonalFollowStatus.BLACK);

				queryPersonalFollow.setTimeEdit(new Date());

				int num = personalFollowManager.update(queryPersonalFollow);

			}

			return ApiResult.newSuccessResult(true);

		} catch (Exception e) {

			log.error(e.getMessage() + e);

			return ApiResult.newErrorResult(
					GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage(), false);

		}
	}

	private List<PersonalFollow> filter(List<PersonalFollow> followList) {

		List<PersonalFollow> list = new ArrayList<PersonalFollow>();

		if (followList == null || followList.size() == 0) {

			return list;
		}

		for (PersonalFollow pf : followList) {

			if (pf.getStatus()
					.equals(AzerothConstants.PersonalFollow.PersonalFollowStatus.NORMAL)) {

				list.add(pf);
			}

			if (pf.getStatus().equals(
					AzerothConstants.PersonalFollow.PersonalFollowStatus.BLACK)) {

				list.add(pf);
			}

		}

		return list;

	}
}

